package user

import (
	"cross-shard-channel/common"
	"github.com/eywa-protocol/bls-crypto/bls"
	"sync"
)

type UserNode struct {
	sync.Mutex // 支持并行操作

	// 主账户密钥
	Pri bls.PrivateKey
	Pub bls.PublicKey

	Channels map[int]*common.Channel
}

var UN UserNode

// 定义对这个结构体的互斥操作

func (un *UserNode)AddNewChannelToNode(cid int, adv bls.PublicKey, advIP string, ourb int, advb int, life int) {
	channel := new(common.Channel)

	channel.Lock()

	// 通道初始状态创建
	channel.Cid = cid
	channel.Adv = adv
	channel.AdvIP = advIP
	channel.MyBalance = ourb
	channel.AdvBalance = advb
	channel.LifeTime = life

	channel.TxCommits = []common.Transaction{}
	channel.TxRefunds = []common.Transaction{}
	channel.TxUnlocks = []common.Transaction{}
	channel.TxPunishs = []common.Transaction{}
	channel.AdvTxCommits = []common.Transaction{}

	channel.AdvLockPubs = []bls.PublicKey{}
	channel.AdvLockPris = []bls.PrivateKey{}
	channel.MyLockPubs = []bls.PublicKey{}
	channel.MyLockPris = []bls.PrivateKey{}

	channel.Unlock()

	un.Channels[cid] = channel
}

func (un *UserNode)RemoveChannel(cid int) {
	delete(un.Channels, cid)
}

func (un *UserNode) Init() {
	un.Lock()
	pr,pu := bls.GenerateRandomKey()
	un.Pub = pu
	un.Pri = pr
	un.Channels = make(map[int]*common.Channel)
	un.Unlock()
}

func (un *UserNode)GetChannelFromNode(cid int) *common.Channel {
	un.Lock()


	ch,ok := un.Channels[cid]
	un.Unlock()

	if !ok {
		return nil
	}
	return ch
}